package com.captain.special.数组;

/**
 * Des:
 *
 * @author XL
 * @Date 2022/4/4 13:52
 */
public class 螺旋矩阵II59 {

    public int[][] generateMatrix(int n) {
        if (n <= 0) return new int[n][];
        int[][] arr = new int[n][n];
        int top = 0;
        int down = arr.length - 1;
        int left = 0;
        int right = arr[0].length - 1;
        int num = 1;
        while (true) {
            //从左向右
            for (int i = left; i <= right; i++) {
                arr[left][i] = num;
                num++;
            }
            top++;
            if (top > down) break;
            //从上往下
            for (int i = top; i <= down; i++) {
                arr[i][right] = num;
                num++;
            }
            right--;
            if (right < left) break;

            //从右往左
            for (int i = right; i >= left; i--) {
                arr[down][i] = num;
                num++;
            }
            down--;
            if (top > down) break;

            //从下往上
            for (int i = down; i >= top; i--) {
                arr[i][left] = num;
                num++;
            }
            left++;
            if (left > right) break;
        }
        return arr;

    }
}
